<template>
  <div class="manager-container">
    <div style="width: 300px;  margin: 0 auto 15px auto ;  display: flex; align-items: center; justify-content: center;">
      <el-button @click="showPrice">{{isShowPrice?'隐藏价格' : '显示价格'}}</el-button>
      <el-button @click="changeSellRecord">{{sellText}}</el-button>
    </div>
    <el-row class="main-panel" >
      <el-col :span="showSell? 4 :0" class="left-panel">
        <el-card v-if="showSell">
          <template #header>
            <div class="card-header">
              <span>请选择商品分类</span>
            </div>
          </template>
          <el-cascader-panel
              placeholder="请选择商品分类"
              v-model="selectOption"
              :options="categories"
              filterable
              clearable
              @change="categoriesChange"
          />
        </el-card>
      </el-col>
      <el-col :span="showSell? 20 :22" :offset="showSell?0:1" class="right-panel">
        <div v-if="showSell">
          <el-table stripe :data="goodsShow" border class="table-container" @rowClick="sellClick"  highlight-current-row >
            <el-table-column prop="name" sortable label="名称" width="250"></el-table-column>
            <el-table-column prop="type_name" sortable label="型号"></el-table-column>
            <el-table-column prop="color" sortable label="颜色"></el-table-column>
            <el-table-column prop="count" label="剩余库存" >
              <template #default="scope">
                <div :style="{color:scope.row.count - scope.row.sell_count == 0 ? 'red' : 'green'}">{{scope.row.count - scope.row.sell_count}}</div>
              </template>
            </el-table-column>
            <el-table-column prop="sell_count" label="已售"></el-table-column>
            <el-table-column v-if="isShowPrice" prop="price" label="价格">
              <template #default="scope">
                <div>{{scope.row.price/200 * 5 > 2 ? Math.floor(scope.row.price/200 * 5 * 100)/100 : 2}}</div>
              </template>
            </el-table-column>
            <el-table-column label="选择数量" width="300">
              <template #default="scope">
                <el-slider v-model="scope.row.sell" show-input :min="0" :max="scope.row.count - scope.row.sell_count" />
              </template>
            </el-table-column>
            <el-table-column label="操作" >
              <template #default="scope">
                <el-button type="primary" @click="changeCrawer(scope.row)">售卖</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-drawer v-model="drawer" title="请确认订单详情" :with-header="false">
            <div class="drawer-container">
              <el-card style="max-width: 480px">
                <template #header>
                  <div class="card-header">
                    <span>请确认订单详情</span>
                  </div>
                </template>
                <el-row class="drawer-container-row">
                  <el-col :span="12">
                    <div>商品名称</div>
                  </el-col>
                  <el-col :span="12">
                    <div>{{order.goods_name}}</div>
                  </el-col>
                </el-row>
                <el-row class="drawer-container-row">
                  <el-col :span="12">
                    <div>售卖数量</div>
                  </el-col>
                  <el-col :span="12">
                    <div :style="{color:order.sell_count == undefined ? 'red' : 'green'}">{{order.sell_count == undefined ? 0 : order.sell_count}}</div>
                  </el-col>
                </el-row>
                <el-row class="drawer-container-row">
                  <el-col :span="12">
                    <div>请输入售卖价格</div>
                  </el-col>
                  <el-col :span="12" >
                    <el-input v-model="order.money" ref="sellInput"  placeholder="请输入售卖价格" clearable @keydown.enter="sellGoods" />
                  </el-col>
                </el-row>
                <el-row class="drawer-container-row">
                  <el-col :span="12">
                    <div>选择售卖方式</div>
                  </el-col>
                  <el-col :span="12">
                    <el-cascader v-model="sellValue" :options="sellType" clearable @change="sellChange"/>
                  </el-col>
                </el-row>
                <el-row class="drawer-container-row" v-if="sellValue === 1">
                  <el-col :span="12">
                    <div>请填写手机号</div>
                  </el-col>
                  <el-col :span="12">
                    <el-input v-model="order.phone" placeholder="请填写手机号" clearable />
                  </el-col>
                </el-row>
                <el-row class="drawer-container-row" v-if="sellValue === 1">
                  <el-col :span="12">
                    <div>请填写手机号</div>
                  </el-col>
                  <el-col :span="12">
                    <el-input v-model="order.address" placeholder="请填写地址" clearable />
                  </el-col>
                </el-row>
                <el-row class="drawer-container-row" >
                  <el-col :span="24">
                    <el-button class="drawer-container-button" @click="sellGoods" type="primary">确认</el-button>
                  </el-col>
                </el-row>
              </el-card>
            </div>
          </el-drawer>
        </div>
        <div v-if="!showSell">
          <Order @flush="flush" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script  setup>

import Order from '@components/Order.vue'
import {invoke} from '@tauri-apps/api'
import {ref, onMounted, reactive, watch, inject, nextTick, getCurrentInstance} from "vue";
import { createId , showMessage , showCustomMessage } from '@/util/index'

// 1. 从挂载的组件中获取到商品集合
let categories = inject("categories") ;
// 1.1 声明默认选择的分类
let selectOption = ref([])
// 1.3.1 声明分类id
let category_id = ref("");
// 1.3.2 声明需要显示的商品集合
let goodsShow = ref([])
// 1.2.1 声明 GoodsVO集合
let goodsVoList = ref([])

// 2.2 售卖记录切换文字
let sellText = ref("查看售卖记录");
// 2.1 是否显示售卖记录
let showSell = ref(true)
// 3. 是否显示价格
let isShowPrice = ref(false)
// 4. 抽屉
let drawer = ref(false)
// 5. 声明订单对象
let order = ref({ id : '' , goods_id : '' , goods_name : '' ,  sell_count : '' , status : '' , money : '' ,  time : '' , phone : '' , address : ''});
// 5.1 售卖方式的选择
let sellType = ref([{'label':'零售','value':0},{'label':'网络','value':1}]);
// 5.1.3 声明绑定售卖变量
let sellValue = ref(0)
// 5.1.4 售卖商品 goods
let good = ref({})
// 5.2 接收父组件传递过来的方法
let emits = defineEmits(['printFlush']);

// 6.1 声明获取输入框对象
let sellInput = ref();

/**
 * 6.1 点击行时切换背景
 */
const sellClick = (row,cell,e)=>{
  console.log(row,cell,e);
}

/**
 * 5.4 定义子组件刷新的方法
 */
const flush = () =>{
  get_goods_result_all();
  emits("printFlush")
}

/**
 * 5.3 修改售卖数量
 * @param goods 商品
 */
const sellGoods = () =>{
  // 修改售卖数量
  if(good.value.sell){
    if(!order.value.money){
      showCustomMessage("请输入价格后再点击确认","error");
    }else {
      if (good.value.count >= good.value.sell_count + good.value.sell){
        order.value.money = order.value.money * 100 ;
        invoke('order_insert',{order:order.value}).then(res=>{
          if(res == 1){
            showMessage(res);
            get_goods_result_all();
            drawer.value = false;
            order.value.money = '' ;
            // 刷新父组件的数据
            emits('printFlush')
          }
        })
      }else{
        showCustomMessage("售卖数量不足",'error')
      }
    }
  }else{
    showCustomMessage("请填写商品数量",'error')
  }
}


/**
 * 5.2 点击售卖时 弹出售卖窗口 并对订单赋值
 * @param goods
 */
const changeCrawer = (goods)=>{
  drawer.value = true;
  good.value = goods ;
  // 添加订单
  let date = new Date();
  order.value.id = createId();
  order.value.goods_id = goods.id;
  order.value.goods_name = goods.name ;
  order.value.sell_count = goods.sell;
  order.value.status = 0;
  order.value.time = date.getTime().toString() ;
  setTimeout(()=>{
    sellInput.value.focus()
  },10)
}

// 5.1.2 售卖方式改变的方法
let sellChange = (value)=>{
  if(value[0]){
    sellValue.value = value[0]
  }
}

/**
 * 3.1 改变显示价格
 */
const showPrice = ()=>{
  isShowPrice.value = !isShowPrice.value;
}

/**
 *  2.3 商品清单与售卖记录切换方法  √
 */
const changeSellRecord = ()=>{
  showSell.value = !showSell.value
  if(showSell.value){
    sellText.value = "查看售卖记录"
  }else{
    sellText.value = "售卖商品"
  }
}

// 1.2.2 获取商品展示集合
const get_goods_result_all = async ()=>{
  invoke('get_goods_result_all').then(res=>{
    if (res.length > 0 ) {
      goodsVoList.value = JSON.parse(res);
    }
  });
}

/**
 * 1.2.4 选择分类得到 商品集合
 * @param e category_id 包装类
 */
const categoriesChange = (e)=>{
  goodsShow.value = [];
  if(e){
    category_id.value = e[0];
    goodsShow.value = goodsVoList.value.filter(goods => {
      return goods.count - goods.sell_count > 0 && goods.category_id == category_id.value
    });
  }
}

// 1.2.3 监听 GoodsVO 集合
watch(goodsVoList , newv =>{
  let goodies = newv ;
  if (goodies[0]) {
    if (category_id.value === ""){ category_id.value = goodies[0].category_id;}
    goodsShow.value = goodies.filter(goods=>{
      return goods.count - goods.sell_count > 0 && category_id.value == goods.category_id
    });
  }
})

// 1.2 监听商品集合的变化
watch(categories , newv =>{
  if(newv[0]){
    selectOption.value = [newv[0].value]
    category_id.value = selectOption.value ;
  }
})

onMounted(()=>{
  get_goods_result_all();
})

defineExpose({get_goods_result_all})
</script>

<style scoped lang="scss">
.manager-container {

  .main-panel{
    width: 98vw;
    .left-panel{
      :deep(.el-card ){
        padding:0 ;
        margin: 0 ;
        .el-card__body{
          padding: 10px ;
          overflow: scroll;

          .el-cascader-panel{
            margin: 0 ;
            .el-cascader-menu{
              width: 100%;
              .el-cascader-menu__wrap{
                width: 100%;
                // 分类显示的高度
                height: 600px;

                .el-scrollbar__view{
                  width: 100%;
                }
              }
            }
          }
        }
      }

    }
    .right-panel{

      .table-container{
        height: 682px;
        border-radius: 5px;
        .el-button{
          opacity: 0.8;
        }
        ::v-deep(.current-row){
          color: rgba(183, 14, 222, 0.5) !important;
          .el-slider__runway{
            background-color: rgba(183, 14, 222, 0.5) ;
          }
          .el-input__inner{
            color: rgba(183, 14, 222) !important;
          }
          .el-button{
            color: #FFF;
            opacity: 1;
          }
        }
      }

      .drawer-container{
        width: 100%;
        .el-card{
          max-height: 700px;

          .drawer-container-row{
            height: 30px;
          }
          .drawer-container-button{
            width: 50%;
            height: 30px;
            margin: 15px 0 0 25%;
          }
        }
      }
    }
  }




}


/*滚动条整体部分*/
.mytable-scrollbar ::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

</style>